package com.dm.server.MQ;

import com.dm.server.service.SeckillVoucherService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Component
public class StockDeductConsumer {
    
    @Resource
    private SeckillVoucherService seckillVoucherService;
    
    /**
     * 消费扣减库存的事务消息
     */
    @RocketMQMessageListener(
        topic = "stock-deduct-topic",
        consumerGroup = "stock-deduct-consumer-group",
        selectorExpression = "deduct"
    )

    public class StockDeductMessageListener implements RocketMQListener<StockDeductMessage> {
        
        @Override
        public void onMessage(StockDeductMessage message) {
            try {
                log.info("收到扣减库存事务消息: {}", message);

                // 执行库存扣减
                boolean success = deductStock(message);
                
                if (success) {
                    log.info("库存扣减成功 - 订单ID: {}, 商品ID: {}", 
                            message.getOrderId(), message.getVoucherId());
                } else {
                    log.error("库存扣减失败 - 订单ID: {}, 商品ID: {}", 
                            message.getOrderId(), message.getVoucherId());
                }
                
            } catch (Exception e) {
                log.error("处理扣减库存消息异常 - 订单ID: {}", message.getOrderId(), e);
            }
        }
    }
    
    /**
     * 扣减库存
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deductStock(StockDeductMessage message) {
        try {
            log.info("开始扣减库存 - 订单ID: {}, 商品ID: {}", 
                    message.getOrderId(), message.getVoucherId());
            
            // 使用乐观锁扣减库存
            boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", message.getVoucherId())
                .gt("stock", 0)
                .update();
            
            if (success) {
                log.info("库存扣减成功 - 订单ID: {}, 商品ID: {}", 
                        message.getOrderId(), message.getVoucherId());
                return true;
            } else {
                log.error("库存扣减失败，库存不足 - 订单ID: {}, 商品ID: {}", 
                        message.getOrderId(), message.getVoucherId());
                return false;
            }
            
        } catch (Exception e) {
            log.error("扣减库存异常 - 订单ID: {}, 商品ID: {}", 
                    message.getOrderId(), message.getVoucherId(), e);
            throw e;
        }
    }
}